package com.xp.basic.heima.nio.netty.simpledemo.chat.client;

import com.xp.basic.heima.nio.netty.simpledemo.chat.message.ChatRequestMessage;
import com.xp.basic.heima.nio.netty.simpledemo.chat.message.ChatResponseMessage;
import com.xp.basic.heima.nio.netty.simpledemo.chat.message.LoginResponseMessage;
import com.xp.basic.heima.nio.netty.simpledemo.chat.message.LoginReuqestMessage;
import com.xp.basic.heima.nio.netty.simpledemo.chat.protocol.MessageCodec;
import com.xp.basic.heima.nio.netty.simpledemo.chat.service.UserServiceFactory;
import com.xp.basic.heima.nio.netty.simpledemo.chat.session.SessionFactory;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.random.RandomGenerator;

public class ChatClientTest {
    public static void main(String[] args) {
        NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();

        //handle
        LoggingHandler LOGGING_HANDLE = new LoggingHandler(LogLevel.DEBUG);
        MessageCodec MESSAGE_CODEC = new MessageCodec();
        CountDownLatch WAIT_FOR_LOGIN = new CountDownLatch(1);
        AtomicBoolean LOGIN_RES = new AtomicBoolean(false);

        try{
            ChannelFuture channelFuture = new Bootstrap()
                    .group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024,12,4,0,0));
                            ch.pipeline().addLast(LOGGING_HANDLE);
                            ch.pipeline().addLast(MESSAGE_CODEC);

                            ch.pipeline().addLast("client-handle",new ChannelInboundHandlerAdapter(){
                                @Override
                                public void channelActive(ChannelHandlerContext ctx) throws Exception {

                                    //在连接建立后触发 active 事件

                                    //负责接收用户在控制台的输入，向服务器发送各种消息
                                    new Thread(()->{
                                        Scanner scanner = new Scanner(System.in);
                                        System.out.println("请输入用户名：");
                                        String userName = scanner.next();
                                        System.out.println("请输入名称：");
                                        String password = scanner.next();
                                        //构造登录消息对象
                                        LoginReuqestMessage reuqestMessage = new LoginReuqestMessage(userName,password);

                                        //发送消息
                                        ctx.writeAndFlush(reuqestMessage);

                                        try {
                                            System.out.println("等待用户输入。。。。。");
//                                            System.in.read();
                                            WAIT_FOR_LOGIN.await();

                                            //如果登录失败，则关闭
                                            if (!LOGIN_RES.get()) {
                                                ctx.channel().close();
                                                return;
                                            }

                                            while (true){
                                                System.out.println("============ 功能菜单 ============");
                                                System.out.println("send [username] [content]");
                                                System.out.println("gsend [group name] [content]");
                                                System.out.println("gcreate [group name] [m1,m2,m3...]");
                                                System.out.println("gmembers [group name]");
                                                System.out.println("gjoin [group name]");
                                                System.out.println("gquit [group name]");
                                                System.out.println("quit");
                                                System.out.println("==================================");
                                                String command = scanner.next();

                                                String[] commandSplit = command.split(",");
                                                switch (commandSplit[0]){
                                                    case "send":
                                                        //发送消息
                                                        ctx.writeAndFlush(new ChatRequestMessage(userName,commandSplit[1],commandSplit[2]));
                                                        break;
                                                    case "gsend":

                                                        break;
                                                    default:
                                                        break;
                                                }
                                            }

                                        } catch (InterruptedException e) {
                                            throw new RuntimeException(e);
                                        }
                                    },"client-active"+ Math.random()).start();



                                }

                                @Override
                                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                    System.out.println(" client rec : "+ msg);

                                    if (msg instanceof LoginResponseMessage) {
                                        LoginResponseMessage loginResponseMessage = (LoginResponseMessage)msg;
                                        if (loginResponseMessage.isSuccess()) {
                                            //登录成功，更改状态
                                            LOGIN_RES.set(true);
                                        }

                                        //唤醒 client-active 线程
                                        WAIT_FOR_LOGIN.countDown();
                                    }else if (msg instanceof ChatResponseMessage chatResponseMessage){
                                        System.out.printf("收到了来自 [%s] 的消息：[%s] %n",chatResponseMessage.getFrom(),chatResponseMessage.getContent());
                                    }


                                }
                            });

                        }
                    })
                    .connect(new InetSocketAddress(8080))
                    .sync();

            try {
                System.in.read();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            channelFuture.channel().closeFuture().sync();

        }catch (Exception e){
            System.out.println(" client error :"+ e.getMessage());

        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }
}
